/**
 * Created by yuyangyang on 2014/8/13.
 */
module.exports = function (grunt) {


    var path = require('path');
    var crc32 = require('buffer-crc32');
    var config = require('../config.json');
    var rId = /\s*define\s*\(\s*(\"|\')([^\"\']+)(\"|\')/i;

    grunt.registerMultiTask('bundles', 'bundles files.', function () {

        var options = this.options({});

        var configStr = grunt.file.read(options.configBuildPath);
        configStr = configStr.trim().replace(/var\s*require\s*=\s*/gi, '');
        var configJson = (new Function('return ' + configStr + ';'))();

        if (!configJson.bundles) {
            configJson.bundles = {};
        }

        this.files.forEach(function (f) {
            var basename = path.basename(f.src.toString());

            grunt.file.recurse(f.src.toString(), function (file) {
                var extname = path.extname(file);


                if (extname !== '.js') {
                    return;
                }
                var moduleId = grunt.file.read(file).match(rId)[2];
                var key, content, signature;

                if (basename === moduleId.split('/')[0]) {
                    content = grunt.file.read(f.src.toString() + '.js');
                    signature = crc32.unsigned(content).toString(16);
                    key = basename + '-' + signature;
                }


                if (!configJson.bundles[key]) {
                    configJson.bundles[key] = [];
                }
                configJson.bundles[key].push(moduleId);

                grunt.file.write(f.orig.dest + '/' + key + '.js', content);

            });
        });

        configJson.baseUrl = config.cdn + configJson.baseUrl;
        grunt.file.write(options.configBuildPath, 'var require=' + JSON.stringify(configJson));

    });
};